<!DOCTYPE html>

<html>

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <title>Barcode Scanner</title>
  <link rel="stylesheet" href="../css/base.css">
  <link rel="stylesheet" type="text/css" href="./css/style.css">
  <style>
    body {
      background: #f8f8f8;
      color: #333;
    }

    #scan {
      height: 40px;
      border-radius: 3px;
      outline: none;
      border: 1px solid #ddd;
    }

    #scan>span:before {
      background-image: #fff;
      width: 0;
      height: 0;
    }
  </style>
  <style>
    #video {
      display: block;
      margin: 1em auto;
      width: 100vw;
      height: auto;
      min-height: 200px;
      max-height: 300px;
    }

    video {
      background: rgba(255, 255, 255, 0.5);
    }

    .grayscale {
      filter: grayscale(1);
    }

    .sepia {
      filter: sepia(1);
    }

    .blur {
      filter: blur(3px);
    }
  </style>
</head>

<body>
  <div style="display: flex;padding: 6px 12px;">
    <span style="flex:1;">
      <input type="text" name="" id="text-1" placeholder="输入条码" style="padding: 0px 6px;height: 30px;line-height:30px;width: 100%;"  />
    </span>
    <span style="width:80px;">
      <button type="button" id="btn" style="outline: none;border: 1px solid #ddd;border-radius: 4px;height: 30px;line-height:30px;width:100%;border-left: none;">扫描</button>
    </span>

  </div>

  <br>
  <br>

  <input type="hidden" id="capture" value="截图" />
  <br>
  <video id="video" autoplay></video>
  <div style="height:300%;"></div>
  <canvas id="canvas" width=300></canvas>
  <select name="video" id="select"></select>
  <script src="https://bluelotos.gitee.io/lib/vconsole/dist/vconsole.min.js"></script>

  <script type="text/javascript" src="../js/jquery.js"></script>
  <script type="text/javascript" src="../layer/layer.js"></script>
  <script type="text/javascript" src="./zbar-processor.js"></script>
  <script>
    var vConsole = new VConsole(),
      scanBarCode = null,
      layerIndex = null;
    const video = document.getElementById('video');
    const button = document.getElementById('btn');
    const select = document.getElementById('select');
    let currentStream;
    var count = 0;
    video.onclick = () => {
      count++;
      switch (count) {
        case 1:
          video.className = 'grayscale';
          break;
        case 2:
          video.className = 'sepia';
          break;
        case 3:
          video.className = 'blur';
          break;
        case 4:
          video.className = '';
          count = 0;
          break;
      }
    }

    function stopMediaTracks(stream) {
      stream.getTracks().forEach(track => {
        track.stop();
      });
    }

    function gotDevices(mediaDevices) {
      select.innerHTML = '';
      select.appendChild(document.createElement('option'));
      let count = 1;
      mediaDevices.forEach(mediaDevice => {
        console.log(mediaDevice)
        if (mediaDevice.kind === 'videoinput') {
          const option = document.createElement('option');
          option.value = mediaDevice.deviceId;
          const label = mediaDevice.label || '摄像头' + (count++);
          const textNode = document.createTextNode(label);
          option.appendChild(textNode);
          select.appendChild(option);
          select.value = mediaDevice.deviceId;
        }
      });

    }

    button.addEventListener('click', event => {
      $("#video").removeClass("hidden").css("display", "block");
      if (typeof currentStream !== 'undefined') {
        stopMediaTracks(currentStream);
      }
      const videoConstraints = {};
      if (select.value === '') {
        videoConstraints.facingMode = 'environment';
      } else {
        videoConstraints.deviceId = {
          exact: select.value
        };
      }
      const constraints = {
        video: videoConstraints,
        audio: false
      };
      navigator.mediaDevices
        .getUserMedia(constraints)
        .then(stream => {
          currentStream = stream;
          video.srcObject = stream;
          video.onloadedmetadata = function (e) {
            video.play();
            scanBarCode = setInterval(function () {
              bindCapture();
            }, 2000)
          };
          return navigator.mediaDevices.enumerateDevices();
        })
        .then(gotDevices)
        .catch(error => {
          console.error(error);
        });
    });

    navigator.mediaDevices.enumerateDevices().then(gotDevices);

    function getScan() {
      if (typeof currentStream !== 'undefined') {
        stopMediaTracks(currentStream);
      }
      const myConstraints = {
        audio: false,
        video: {
          facingMode: "environment"
        }
        /* video: {
            facingMode: {
                exact: "environment"
            },
            height: 300,
            frameRate: {
                ideal: 10,
                max: 15
            }
        } */
      }
      navigator.mediaDevices.getUserMedia(myConstraints)
        .then(function (mediaStream) {
          // 旧的浏览器可能没有srcObject
          if ("srcObject" in video) {
            video.srcObject = mediaStream;
          } else {
            // 防止再新的浏览器里使用它，应为它已经不再支持了
            // createObjectURL是个非常有用的API，诸位可以多研究研究
            video.src = window.URL.createObjectURL(mediaStream);
          }
          video.onloadedmetadata = function (e) {
            video.play();
            bindCapture();
          };
        })
        .catch(function (err) {
          console.log(err.name + ": " + err.message);
        }); // 总是在最后检查错误
    }

    function bindCapture() {
      layer.close(layerIndex);
      layerIndex = layer.load(2, {
        time: 2 * 1000
      });
      var videoWidth = 300,
        videoHeight = 300 / video.videoWidth * video.videoHeight;
      if (videoWidth && videoHeight) {
        var canvas = document.getElementById('canvas');
        canvas.width = videoWidth;
        canvas.height = videoHeight;
        var ctx = canvas.getContext('2d');
        ctx.drawImage(video, 0, 0, videoWidth, videoHeight);

        var data = ctx.getImageData(0, 0, canvas.width, canvas.height);

        var t0 = Date.now();
        var codes = zbarProcessImageData(data);
        var t = Date.now() - t0;
        document.body.classList.remove('processing');

        if (codes.length === 0) {
          console.log("识别失败，请重试!")
          document.body.classList.add('not-detected');
          return;
        } else {
          $("#video").addClass("hidden").css("display", "none");
          layer.close(layerIndex);
          layer.msg("识别成功！");
          clearInterval(scanBarCode)
          stopMediaTracks(currentStream)
        }

        var data1 = codes[0][2];
        // publishing data
        $("#text-1")[0].value = data1;


        document.getElementById('capture').addEventListener(
          'click',
          function () {
            canvas.getContext('2d').drawImage(
              video, 0, 0, videoWidth, videoHeight
            );
          },
          false
        );
      } else {
        setTimeout(bindCapture, 200);
      }
    }

    function shoot() {
      var canvas = document.createElement('canvas');
      canvas.width = 640;
      canvas.height = 480;
      var ctx = canvas.getContext('2d');
      ctx.drawImage(video, 0, 0);
      canvas.toBlob((myblob) => {
        download(myblob);
      });
    }

    function download(blob) {
      var a = document.createElement('a');
      a.href = URL.createObjectURL(blob);
      a.download = Math.random().toString(36).substr(2, 14);
      a.click();
    }
  </script>
</body>

</html>